package main;

import game.Game;
import dialog.BeautyContestOpt;
import dialog.CentipedeOpt;
import dialog.DictatorOpt;
import dialog.DilemmaOpt;
import dialog.ImpulseOpt;
import dialog.LotteryOpt;
import dialog.PenelopeOpt;
import dialog.PublicGoodsOpt;
import dialog.QuestionnaireOpt;
import dialog.TrustDictatorOpt;
import dialog.TrustOpt;
import dialog.UltimatumOpt;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Vector;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/*
 * ConfigScreen.java
 *
 * Created on Mar 1, 2009, 2:09:13 PM
 */

/**
 *
 * @author Vinay
 */
public class ConfigScreen extends javax.swing.JFrame {
    static Vector<String> gameParamList = new Vector();
    static Game g = new Game();
    Dimension screenSize;

    /** Creates new form ConfigScreen */
    public ConfigScreen() {
        this.setUndecorated(true);
        screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        initComponents();
        this.setVisible(true);
        jLabel1.setText("Player ID  :  "+g.playerId);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        btnDefault = new javax.swing.JButton();
        btnRemove = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        lstTo = new javax.swing.JList();
        btnAdd = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstFrom = new javax.swing.JList();
        btnLoad = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        btnStart = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setAlwaysOnTop(true);
        setResizable(false);

        btnDefault.setFont(new java.awt.Font("Tahoma", 0, 12));
        btnDefault.setText("Set Default");
        btnDefault.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDefaultActionPerformed(evt);
            }
        });

        btnRemove.setText("<<");
        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });

        lstTo.setFont(new java.awt.Font("Tahoma", 0, 13));
        lstTo.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(lstTo);

        btnAdd.setText(">>");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        lstFrom.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
        lstFrom.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Penelope", "Impulse", "Lottery", "Dictator", "Ultimatum", "Trust", "Trust-Dictator", "Centipede", "Dilemma", "Beauty-Contest", "Public-Goods", "Questionnaire" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        lstFrom.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(lstFrom);

        btnLoad.setFont(new java.awt.Font("Tahoma", 0, 12));
        btnLoad.setText("Load");
        btnLoad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoadActionPerformed(evt);
            }
        });

        btnSave.setFont(new java.awt.Font("Tahoma", 0, 12));
        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 185, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jPanel2Layout.createSequentialGroup()
                        .add(64, 64, 64)
                        .add(btnLoad, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 87, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 72, Short.MAX_VALUE)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
                    .add(btnAdd)
                    .add(btnRemove)
                    .add(btnDefault))
                .add(89, 89, 89)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jPanel2Layout.createSequentialGroup()
                        .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 185, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .add(jPanel2Layout.createSequentialGroup()
                        .add(btnSave, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 89, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(57, 57, 57))))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel2Layout.createSequentialGroup()
                        .add(85, 85, 85)
                        .add(btnAdd)
                        .add(29, 29, 29)
                        .add(btnRemove)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 90, Short.MAX_VALUE)
                        .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(btnDefault)
                            .add(btnLoad)
                            .add(btnSave)))
                    .add(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)
                            .add(jScrollPane2))))
                .addContainerGap())
        );

        btnStart.setFont(new java.awt.Font("Tahoma", 0, 14));
        btnStart.setText("Start");
        btnStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStartActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Calibri", 1, 28));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Player ID  :  ");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(layout.createSequentialGroup()
                            .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 828, Short.MAX_VALUE)
                            .addContainerGap())
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(81, 81, 81)))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(btnStart, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 136, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(344, 344, 344))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(26, 26, 26)
                .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 121, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 37, Short.MAX_VALUE)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(56, 56, 56)
                .add(btnStart, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 55, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(47, 47, 47))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	/**
	 * Opens a dialog box with all the options for a particular game, and then
	 * returns the comma-separated list of parameters for that game.
	 *
	 * @param game	The name of the game whose options dialog box we want.
	 * @return		A list of parameters for the game.
	 */
    private String getGameParam(String game) {
        if (game.equals("Penelope")) {
			dialog.PenelopeOpt dBox = new PenelopeOpt(this, true);
			dBox.setLocation((screenSize.width - dBox.getWidth())/2,
				(screenSize.height - dBox.getHeight())/2);
			dBox.setVisible(true);
			return dBox.getParamsList();
        }
		else if(game.equals("Impulse")) {
			dialog.ImpulseOpt dBox = new ImpulseOpt(this, true);
			dBox.setLocation((screenSize.width - dBox.getWidth())/2,
				(screenSize.height - dBox.getHeight())/2);
			dBox.setVisible(true);
			return dBox.getParamsList();
        }
		else if(game.equals("Lottery")) {
			dialog.LotteryOpt dBox = new LotteryOpt(this, true);
			dBox.setLocation((screenSize.width - dBox.getWidth())/2,
				(screenSize.height - dBox.getHeight())/2);
			dBox.setVisible(true);
           return dBox.getParamsList();
        }
		else if(game.equals("Dictator")) {
            dialog.DictatorOpt dBox = new DictatorOpt(this, true);
            dBox.setLocation((screenSize.width - dBox.getWidth())/2,
				(screenSize.height - dBox.getHeight())/2);
			dBox.setVisible(true);
            return dBox.getParamsList();
        }
		else if(game.equals("Ultimatum")) {
            dialog.UltimatumOpt dBox = new UltimatumOpt(this, true);
            dBox.setLocation((screenSize.width - dBox.getWidth())/2,
				(screenSize.height - dBox.getHeight())/2);
			dBox.setVisible(true);
            return dBox.getParamsList();
        }
		else if(game.equals("Trust")) {
            dialog.TrustOpt dBox = new TrustOpt(this, true);
            dBox.setLocation((screenSize.width - dBox.getWidth())/2,
				(screenSize.height - dBox.getHeight())/2);
			dBox.setVisible(true);
            return dBox.getParamsList();
        }
		else if(game.equals("Trust-Dictator")) {
            dialog.TrustDictatorOpt dBox = new TrustDictatorOpt(this, true);
            dBox.setLocation((screenSize.width - dBox.getWidth())/2,
				(screenSize.height - dBox.getHeight())/2);
			dBox.setVisible(true);
            return dBox.getParamsList();
        }
		else if(game.equals("Centipede")) {
            dialog.CentipedeOpt dBox = new CentipedeOpt(this, true);
            dBox.setLocation((screenSize.width - dBox.getWidth())/2,
				(screenSize.height - dBox.getHeight())/2);
			dBox.setVisible(true);
            return dBox.getParamsList();
        }
        else if(game.equals("Dilemma")) {
            dialog.DilemmaOpt dBox = new DilemmaOpt(this, true);
            dBox.setLocation((screenSize.width - dBox.getWidth())/2,
				(screenSize.height - dBox.getHeight())/2);
			dBox.setVisible(true);
            return dBox.getParamsList();
        }
        else if(game.equals("Beauty-Contest")) {
            dialog.BeautyContestOpt dBox = new BeautyContestOpt(this, true);
            dBox.setLocation((screenSize.width - dBox.getWidth())/2,
				(screenSize.height - dBox.getHeight())/2);
			dBox.setVisible(true);
            return dBox.getParamsList();
        }
		else if(game.equals("Public-Goods")) {
            dialog.PublicGoodsOpt dBox = new PublicGoodsOpt(this, true);
            dBox.setLocation((screenSize.width - dBox.getWidth())/2,
				(screenSize.height - dBox.getHeight())/2);
			dBox.setVisible(true);
            return dBox.getParamsList();
        }
        else if (game.equals("Questionnaire")) {
            dialog.QuestionnaireOpt dBox = new QuestionnaireOpt(this, true);
            dBox.setLocation((screenSize.width - dBox.getWidth())/2,
				(screenSize.height - dBox.getHeight())/2);
			dBox.setVisible(true);
            return dBox.getParamsList();
        }
        else {
            return "NULL";
        }
    }

    public Vector<String> getGameParamsList() {
        return gameParamList;
    }

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        String game = lstFrom.getSelectedValue().toString();
        String params = getGameParam(game);
        gameParamList.add(game+","+params);
        lstTo.setListData(gameParamList);
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
        if(!lstTo.isSelectionEmpty()) {
            gameParamList.remove(lstTo.getSelectedIndex());
            lstTo.setListData(gameParamList);
        }
    }//GEN-LAST:event_btnRemoveActionPerformed

    private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartActionPerformed
        if(gameParamList.size()==0) {
            JOptionPane.showMessageDialog(this, "No Games have been selected","",JOptionPane.WARNING_MESSAGE);
        }
        else {
            this.setVisible(false);
            g.free=true;
            //startGames();
        }
}//GEN-LAST:event_btnStartActionPerformed

    private void btnDefaultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDefaultActionPerformed
        setDefault();
    }//GEN-LAST:event_btnDefaultActionPerformed

    private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadActionPerformed
        JFileChooser fileChooser = new JFileChooser(new File("."));
        fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        fileChooser.addChoosableFileFilter(new CfgFilter());

        fileChooser.showOpenDialog(this);
        if(fileChooser.getSelectedFile() != null)
            loadCFG(fileChooser.getSelectedFile().getAbsolutePath());
}//GEN-LAST:event_btnLoadActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        if(gameParamList.size()==0){
            JOptionPane.showMessageDialog(this,
                "There are no games selected to save.",
                "Save Configuration",
                JOptionPane.WARNING_MESSAGE);
        }
        else {
            JFileChooser fileChooser = new JFileChooser(new File("."));
            fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
            fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            fileChooser.addChoosableFileFilter(new CfgFilter());

            fileChooser.showSaveDialog(this);
            if(fileChooser.getSelectedFile() != null)
                saveCFG(fileChooser.getSelectedFile().getAbsolutePath());
        }
}//GEN-LAST:event_btnSaveActionPerformed

    private void setDefault() {
        try {
            gameParamList.removeAllElements();
            BufferedReader br = new BufferedReader(new FileReader("config/default.cfg"));
            String line = null;
            br.readLine();
            while ((line = br.readLine()) != null) {
                gameParamList.add(line);
            }
            lstTo.setListData(gameParamList);
        }
        catch(Exception ex) {
            ex.printStackTrace();
            g.logError(ex);
        }
    }

    private void loadCFG(String filePath) {
        BufferedReader br = g.readFile(filePath);
        try {
            String verify = br.readLine();
            if(verify.equals("&!^$#%*#*^#!)*$()(^%")) {
                String line = null;
                
                while ((line = br.readLine()) != null) {
                    gameParamList.add(line);
                }
                lstTo.setListData(gameParamList);
            }
            else {
                JOptionPane.showMessageDialog(this,
                filePath+" is not of the correct format or is corrupted.",
                "Load Configuration",
                JOptionPane.ERROR_MESSAGE);
            }
        } catch(Exception ex) {
            ex.printStackTrace();
            g.logError(ex);
        }
    }

    private void saveCFG(String filePath) {
        g.writeFile(filePath+".cfg", "&!^$#%*#*^#!)*$()(^%");
        for(int i=0; i<gameParamList.size(); i++) {
            g.writeFile(filePath+".cfg", gameParamList.get(i));
        }
    }

class CfgFilter extends javax.swing.filechooser.FileFilter {
      public boolean accept(File file) {
        String filename = file.getName();
        return filename.endsWith(".cfg");
      }

      public String getDescription() {
        return "*.cfg";
      }
}

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ConfigScreen().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDefault;
    private javax.swing.JButton btnLoad;
    private javax.swing.JButton btnRemove;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnStart;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList lstFrom;
    private javax.swing.JList lstTo;
    // End of variables declaration//GEN-END:variables

}
